#include "game_log.h"
#include <string.h>
#include "game_file.h"
#include "game_macros.h"
#include "game_timer.h"
#include <unistd.h>
#include "game_ev.h"

CGame::Logger::StdoutLoggerFactory g_LoggerFactory;

CGameLoggerFactory* CGameLoggerFactory::getInstance(){
  return &g_LoggerFactory;
}


class TimerLogger{
private:
  CGameTimer* _timer;
  int _count;
public:
  TimerLogger(CGameTimer* timer):_timer(timer),_count(0){};
  BOOL onTimer(CGameEvent* evt);
  BOOL onComplete(CGameEvent* evt);
};

BOOL TimerLogger::onTimer(CGameEvent* evt){
  CC_LOG("TimerLogger","%s","tick");
  _count++;

  if(_count >= 6){
    _timer->stop();
  }
}

BOOL TimerLogger::onComplete(CGameEvent* evt){
  CC_LOG("TimerLogger","%s","complete");
}

int main()
{
  int ret = 0;

  do{

    CC_BREAK_IF(!g_LoggerFactory.init());

    char cwd[C_MAX_FILENAME];
    __getcwd(cwd,C_MAX_FILENAME);
    std::string str{cwd};
    str += "/../..";

    CC_LOG("main","%s","run");

    CGameTimer timer;
    timer.init(1000,10);

    TimerLogger logger{&timer};
    timer.addEventListener(CGameTimerEvent::TIMER,CGameEventHandler(&logger,&TimerLogger::onTimer));
    timer.addEventListener(CGameTimerEvent::TIMER_COMPLETE,CGameEventHandler(&logger,&TimerLogger::onComplete));

    do{
      event_base_loop(g_CGameEV.getBase(), EVLOOP_NONBLOCK);
      // doRun();
      // *((uint8_t*)(0x0)) = 1; // segv error test
      ::usleep(40 * 1000);
    }while(true);

    return ret;
  }while(true);


  return ret;
}
